package com.anycc.cloud.gateway.service.impl;

import com.anycc.cloud.gateway.service.PermissionService;
import com.anycc.cloud.gateway.service.feign.RolePermissionService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 网关鉴权实现类
 */
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {
    private static final Logger LOG = LoggerFactory.getLogger(PermissionServiceImpl.class);

    private static final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS";
    private static final String HTTP_METHOD_OPTIONS = "OPTIONS";

    @Value("#{'${anycc.security.authority.check-list}'.split(',')}")
    private List<String> authorityStringList;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        System.out.println(authorityStringList);
        if (HTTP_METHOD_OPTIONS.equals(request.getMethod())) {//直接放行AJAX跨域预警探测
            return true;
        }
        Object principal = authentication.getPrincipal();
        List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
        if (principal == null) {
            return false;
        }
        if (grantedAuthorityList == null || grantedAuthorityList.isEmpty()) {
            LOG.warn("角色列表为空：{}", authentication.getPrincipal());
            return false;
        }
        if (authorityStringList.stream().anyMatch(authorityString -> StringUtils.lowerCase(request.getRequestURI()).contains(authorityString))) {
            List<String> roleNames = new ArrayList<>();
            grantedAuthorityList.forEach(authority -> {
                if (!ROLE_ANONYMOUS.equalsIgnoreCase(authority.getAuthority())) {
                    roleNames.add(authority.getAuthority());
                }
            });
            List<String> rolePermissionStrings = rolePermissionService.findFullPermissionString(roleNames);
            System.out.println(rolePermissionStrings);
            System.out.println(request.getRequestURI());
            return rolePermissionStrings.contains(StringUtils.upperCase(
                    request.getRequestURI().startsWith("/") ? request.getRequestURI().substring(1) : request.getRequestURI()));
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println("/area".substring(1));
    }

}
